import React, { FC, useContext, useEffect, useMemo } from 'react'
import { Modal, Form, Input, Select, Upload, Button, message } from 'antd'
import { ModalProps } from 'antd/lib/modal'
import { rulesMessage, ERules } from '../../../constant'
import { UploadOutlined } from '@ant-design/icons';
import { UploadProps, RcFile } from 'antd/lib/upload';
import useRequest from '../../../hooks/useRequest';
import { Context } from '../index';
import { ActionState } from '../../../store/usePicStore';
import { useForm } from 'antd/lib/form/Form';
import { Option } from 'antd/lib/mentions';
import PrivideResolution from './PrivideResolution';

interface Request {
    configPic: (parmas: any) => Promise<any>
}
interface IProps extends ModalProps {
    handleOk?: () => void
    handleCancel?: () => void
}

const defaultFormProps = {
    labelAlign: 'right' as any,
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
}

const defaultUploadProps: UploadProps = {
    action: `${BASE_URL}/pics/uploadImg`,
    listType: 'picture',

};

const NewPicModal: FC<IProps> = ({ handleOk, handleCancel, confirmLoading }) => {
    const [formRef] = useForm()
    const request = useRequest<Request>({ modulePath: 'pic' })
    const { state, dispatch } = useContext(Context)
    const { visible, id, formData, classify } = state
    const onOk = () => {
        formRef.validateFields().then(async ({ img_url, author, pic_name, max_width,
            max_height, privide_resolution, classify }: any) => {
            const body = {
                img_url: img_url.file.response.data.path,
                author,
                pic_name,
                max_width,
                max_height,
                privide_resolution: JSON.stringify(privide_resolution),
                classify,
                img_info: JSON.stringify(img_url.file)
            }
            const res = await request.configPic(body)
            if (res) {
                message.success('操作成功')
                handleOk && handleOk()
            }

        }).catch(e => {
            console.log(e)
        })

    }
    const onCancel = () => {
        handleCancel && handleCancel()
    }
    const afterClose = () => {
        formRef.resetFields()
        dispatch({ type: ActionState.SET_FORM_DATA, payload: formRef.getFieldsValue() })
    }
    // useEffect(() => {
    //     formRef.setFieldsValue(formData)
    // }, [formData])
    useEffect(() => {
        if (visible && id) {
            console.log(Object.assign(JSON.parse(formData.img_info), { url: formData.img_url }))
            const img_url = formData.img_info ? Object.assign(JSON.parse(formData.img_info), { url: formData.img_url }) : []
            // formRef.setFieldsValue({
            //     pic_name: formData.pic_name,
            //     author: formData.author,
            //     img_url: formData.img_info ? Object.assign(JSON.parse(formData.img_info), { url: formData.img_url }) : [],
            //     max_width: formData.max_width,
            //     max_height: formData.max_height,
            //     classify: formData.classify.map((item: any) => item.id)
            // })
            // console.log(formRef.getFieldsValue())

        }
    }, [visible])
    const clasifyOptions = useMemo(() => {
        return classify && classify.map(item => <Option value={item.id.toString()}>{item.classify_name}</Option>)
    }, [classify])
    // 上传之前获取图片宽高
    const beforeUpload = (file: RcFile) => {
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
            const image = new Image();
            image.src = reader.result as string;
            image.onload = () => {
                let w = image.width;
                let h = image.height;
                console.log("宽高：", w, h);
                console.log(formRef.getFieldValue('privide_resolution'))
                formRef.setFieldsValue({
                    ...formRef.getFieldsValue(),
                    max_width: w,
                    max_height: h,
                    // privide_resolution: [...formRef.getFieldValue('privide_resolution'), `${w}*${h}`]
                })
            }
        }
        return true;
    }

    return <Modal
        title={id === 0 ? '上传图片' : '修改图片'}
        visible={visible}
        onOk={onOk}
        confirmLoading={confirmLoading}
        onCancel={onCancel}
        destroyOnClose={true}
        afterClose={afterClose}
    >
        <Form {...defaultFormProps} form={formRef}>
            <Form.Item
                label="图片名称"
                name="pic_name"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, '图片名称') }]}
            >
                <Input placeholder="请输入图片名称" />
            </Form.Item>
            <Form.Item
                label="作者"
                name="author"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, '作者') }]}
            >
                <Input placeholder="请输入作者" />
            </Form.Item>
            <Form.Item
                label="图片上传"
                name="img_url"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, '图片上传') }]}
            >
                <Upload {...defaultUploadProps} beforeUpload={beforeUpload}>
                    <Button>
                        <UploadOutlined /> Upload
                    </Button>
                </Upload>
            </Form.Item>
            <Form.Item
                label="max_width"
                name="max_width"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, 'max_width') }]}
            >
                <Input placeholder="请输入宽度" />
            </Form.Item>
            <Form.Item
                label="max_height"
                name="max_height"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, 'max_height') }]}
            >
                <Input placeholder="请输入高度" />
            </Form.Item>
            <PrivideResolution></PrivideResolution>
            <Form.Item
                label="分类"
                name="classify"
                rules={[{ required: true, message: rulesMessage(ERules.REQUIRED, '分类') }]}
            >
                <Select placeholder="请选择" mode="multiple">{clasifyOptions}</Select>
            </Form.Item>
        </Form>
    </Modal >
}

export default NewPicModal